import os  # noqa
import time

# Get an access_token through personal access token oroauth.
coze_api_token = 'pat_GHGl2hWfDkm85Pe8Zd4E7N8yXfadWdyH4xnLMabPnSmGfKxy9LbtYjyRugDjtc4q'

from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType  # noqa
from cozepy import COZE_CN_BASE_URL
# Init the Coze client through the access_token.
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=COZE_CN_BASE_URL)

# Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
bot_id = "7434130335103418420"
# The user id identifies the identity of a user. Developers can use a custom business ID
# or a random string.
user_id = "2795378230442956"

# Call the coze.chat.stream method to create a chat. The create method is a streaming
# chat and will return a Chat Iterator. Developers should iterate the iterator to get
# chat event and handle them.
# for event in coze.chat.stream(
#     bot_id=bot_id, user_id=user_id, additional_messages=[Message.build_user_question_text("How are you?")]
# ):
#     if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
#         message = event.message
#         print(f"role={message.role}, content={message.content}")


chat = coze.chat.create(
        bot_id=bot_id,
        user_id=user_id,
        additional_messages=[
            Message.build_user_question_text("python学习路线是怎样的？"),
        ],
    )

# Assume the development allows at most one chat to run for 10 minutes. If it exceeds 10
# minutes, the chat will be cancelled.
# And when the chat status is not completed, poll the status of the chat once every second.
# After the chat is completed, retrieve all messages in the chat.
start = int(time.time())
timeout = 600
while chat.status == ChatStatus.IN_PROGRESS:
    if int(time.time()) - start > timeout:
        # too long, cancel chat
        coze.chat.cancel(conversation_id=chat.conversation_id, chat_id=chat.id)
        break

    time.sleep(1)
    # Fetch the latest data through the retrieve interface
    chat = coze.chat.retrieve(conversation_id=chat.conversation_id, chat_id=chat.id)

# When the chat status becomes completed, all messages under this chat can be retrieved through the list messages interface.
messages = coze.chat.messages.list(conversation_id=chat.conversation_id, chat_id=chat.id)
for message in messages:
    print(f"role={message.role}, content={message.content}")